(function () {

    $(document).ready(function () {
        var contactType = "Adopt";

        $('.adoptionButton').on('click', function () {
            $('#contactForm').modal();
            contactType = "Adopt";
        });

        $('.brithButton').on('click', function () {
            $('#contactForm').modal();
            contactType = "Brith";
        });

        $('#cancelContact').on('click', function () {
            $('.simplemodal-close').click();
        });

        $('#additionalMessage').keypress(function (e) {
            var tval = $('#additionalMessage').val();
            var tlength = tval.length;
            var set = 400;
            remain = parseInt(set - tlength);
            $('#remainChars').text(remain);

            if (remain <= 0 && e.which !== 0 && e.charCode !== 0) {
                $('#additionalMessage').val((tval).substring(0, tlength - 1))
            }
        });

        $('#sendContact').on('click', function () {
            $.ajax({
                type: "POST",
                url: $('#ContactURL').val(),
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify({
                    DestinationUserID: $('#DestinationID').val(),
                    PetName: $('#TargetPet').val(),
                    ContactType: contactType,
                    AdditionalMessage: $('#additionalMessage').val()
                }),
                success: function (result) {
                    $('.formContent').fadeOut('fast', function() {
                        $('.okMessage').fadeIn('slow');
                    });
                    setTimeout(function () {
                        $('.simplemodal-close').click();
                    }, 2000);
                },
                error: function (xhr, status, msg) {
                    alert("Se ha producido un error al intentar enviar el mensaje.");
                }
            });
        });
    });
})();